<?php

namespace app\admin\controller;

use app\admin\model\User;
use app\common\controller\Backend;
use app\common\model\User as UserM;
use Kreait\Firebase\Factory;
use Kreait\Firebase\Messaging\CloudMessage;
use Kreait\Firebase\Messaging\Notification;
use think\Db;
use Throwable;

/**
 * 试骑管理
 *
 * @icon fa fa-circle-o
 */
class Tryride extends Backend
{

    /**
     * Tryride模型对象
     * @var \app\admin\model\Tryride
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Tryride;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $params = $this->request->param();
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            
            $filter = json_decode($params['filter'],true);
            if (isset($filter['applyuid'])&&$filter['applyuid'] || isset($filter['touid'])&&$filter['touid']) {
                $where = [];
            }
            if (isset($filter['applyuid'])&&$filter['applyuid']) {
                $ids = Db::name('user')->where(['username'=>['like','%'.$filter['applyuid'].'%']])->column('id');
                $where['applyuid'] = ['in',$ids];
            }
            if (isset($filter['touid'])&&$filter['touid']) {
                $ids = Db::name('user')->where(['username'=>['like','%'.$filter['touid'].'%']])->column('id');
                $where['touid'] = ['in',$ids];
            }
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list  = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as &$value) {
                $applystatus = '';
                $tostatus    = '';
                if ($value['applystatus'] == 1) {
                    $applystatus = '<span class="text-success">'.lang('Status 1').'</span>';
                } elseif ($value['applystatus'] == 2) {
                    $applystatus = '<span class="text-danger">'.lang('Status 2').'</span>';
                } elseif ($value['applystatus'] == 3) {
                    $applystatus = '<span class="text-warning">'.lang('Status 3').'</span>';
                }
                if ($value['tostatus'] == 1) {
                    $tostatus = '<span class="text-success">'.lang('Status 1').'</span>';
                } elseif ($value['tostatus'] == 2) {
                    $tostatus = '<span class="text-danger">'.lang('Status 2').'</span>';
                } elseif ($value['tostatus'] == 3) {
                    $tostatus = '<span class="text-warning">'.lang('Status 3').'</span>';
                }
                $applyname          = Db::name('user')->where('id', $value['applyuid'])->value('name');
                $toname             = Db::name('user')->where('id', $value['touid'])->value('name');
                $applyregion        = Db::name('user')->where('id', $value['applyuid'])->value('region');
                $toregion           = Db::name('user')->where('id', $value['touid'])->value('region');
                $value['applyuid'] = $applyname . '-' . $applyregion . '-' . $applystatus;
                $value['touid']    = $toname . '-' . $toregion . '-' . $tostatus;
                $hour               = intval($value['time_unit']) >= 3600 ? floatval(sprintf('%.2f', $value['time_unit'] / 3600)) . 'hours' : $value['time_unit'];
                $value['time_unit'] = intval($value['time_unit']) >= 86400 ? floatval(sprintf('%.2f', $value['time_unit'] / 86400)) . 'day' : $hour;
            }
            unset($value);
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();

    }

    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            if ($this->modelValidate) {
                $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $domain = $this->request->domain();
            $word   = 'api.emojobike.com';
            if (str_contains($domain, $word)) {
                $push_result_shenqingren    = $this->tryRideSend($params['applyuid'], '申请人');
                $push_result_beishenqingren = $this->tryRideSend($params['touid'], '被申请人');
            } else {
                $push_result_shenqingren = $push_result_beishenqingren = "域名不包含{$word}所以不执行";
            }
            $result = $this->model->allowField(true)->save($params + [
                    'push_result_shenqingren'    => $push_result_shenqingren,
                    'push_result_beishenqingren' => $push_result_beishenqingren,
                ]);
            Db::commit();
        } catch (Throwable $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            if ($this->modelValidate) {
                $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $domain = $this->request->domain();
            $word   = 'api.emojobike.com';
            if (str_contains($domain, $word)) {
                $push_result_shenqingren    = $this->tryRideSend($params['applyuid'], '申请人');
                $push_result_beishenqingren = $this->tryRideSend($params['touid'], '被申请人');
            } else {
                $push_result_shenqingren = $push_result_beishenqingren = "域名不包含{$word}所以不执行";
            }
            $result = $row->allowField(true)->save($params + [
                    'push_result_shenqingren'    => $push_result_shenqingren,
                    'push_result_beishenqingren' => $push_result_beishenqingren,
                ]);
            Db::commit();
        } catch (Throwable $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function userlist($ids = null)
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $where2 = [];
            if ($ids) {
                $where2['applyuid|touid'] = $ids;
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where($where2)
                ->order($sort, $order)
                ->count();
            $list  = $this->model
                ->where($where)
                ->where($where2)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as &$value) {
                $applystatus = '';
                $tostatus    = '';
                if ($value['applystatus'] == 1) {
                    $applystatus = '<span class="text-success">'.lang('Status 1').'</span>';
                } elseif ($value['applystatus'] == 2) {
                    $applystatus = '<span class="text-danger">'.lang('Status 2').'</span>';
                } elseif ($value['applystatus'] == 3) {
                    $applystatus = '<span class="text-warning">'.lang('Status 3').'</span>';
                }
                if ($value['tostatus'] == 1) {
                    $tostatus = '<span class="text-success">'.lang('Status 1').'</span>';
                } elseif ($value['tostatus'] == 2) {
                    $tostatus = '<span class="text-danger">'.lang('Status 2').'</span>';
                } elseif ($value['tostatus'] == 3) {
                    $tostatus = '<span class="text-warning">'.lang('Status 3').'</span>';
                }
                $applyname = Db::name('user')->where('id', $value['applyuid'])->value('name');
                $toname    = Db::name('user')->where('id', $value['touid'])->value('name');
                //高亮
                if ($value['applyuid'] == $ids) {
                    $applyname = '<span class="label label-warning">' . $applyname . '</span>';
                }
                if ($value['touid'] == $ids) {
                    $toname = '<span class="label label-warning">' . $toname . '</span>';
                }
                $applyregion        = Db::name('user')->where('id', $value['applyuid'])->value('region');
                $toregion           = Db::name('user')->where('id', $value['touid'])->value('region');
                $value['applyname'] = $applyname . '-' . $applyregion . '-' . $applystatus;
                $value['toname']    = $toname . '-' . $toregion . '-' . $tostatus;

                $hour               = intval($value['time_unit']) >= 3600 ? floatval(sprintf('%.2f', $value['time_unit'] / 3600)) . 'hours' : $value['time_unit'];
                $value['time_unit'] = intval($value['time_unit']) >= 86400 ? floatval(sprintf('%.2f', $value['time_unit'] / 86400)) . 'days' : $hour;
            }
            unset($value);
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        $this->assign("id", $ids);
        return $this->view->fetch();

    }


    public function getuser()
    {

        $params = $this->request->post();
        $user   = new User;
        $where  = [];
        if ($this->request->request('keyValue')) {
            $where['id'] = ['=', $this->request->request('keyValue')];
        }
        if (isset($params['custom']['uid'])) {
            $region = Db::name('user')->where('id', $params['custom']['uid'])->value('region');
            if ($region) {
                $region = explode(',', $region);
                //$where['region'] = ['like','%'.$region[count($region)-1].'%'];
            }
        }
        if (isset($params['custom']['sqr'])) {
            if ($params['custom']['sqr'] == 0) {
                $where['tryride'] = 1;
            }
        }
        $tryrideinfo = [];
        if (isset($params['custom']['uid']) && isset($params['custom']['sqr'])) {
            //查询历史试骑信息
            if ($params['custom']['sqr'] == 0) {
                $tryrideinfo = Db::name('tryride')
                    ->where(['touid' => $params['custom']['uid']])
                    ->field('tomobile as mobile,toaddress as address')
                    ->find();
            } else {
                $tryrideinfo = Db::name('tryride')
                    ->where(['applyuid' => $params['custom']['uid']])
                    ->field('applymobile as mobile,applyaddress as address')
                    ->find();
            }

        }
        if (isset($params['name'])) {
            $where['nickname|region'] = ['like', '%' . $params['name'] . '%'];
        }
        if (!isset($params['pageNumber'])) {
            $params['pageNumber'] = 1;
        }

        if (!isset($params['pageSize'])) {
            $params['pageSize'] = 10;
        }

        $list = $user->where(['status' => 'normal', 'username' => ['<>', 'admin']])
            ->where($where)
            ->field('id,nickname,name,gender,region')
            ->limit(($params['pageNumber'] - 1) * $params['pageSize'], $params['pageSize'])
            ->select();
        //$list =[];
        $n = 0;
        foreach ($list as &$value) {
            $gender        = $value['gender'] == 0 ? lang('Woman') : lang('Man');
            $value['name'] = $value['name'] . '-' . $gender . '-' . $value['region'];
            //$whereOr = ['applyuid'=>$value['id'],'status'=>['in','0,1']];
            // $tryride = Db::name('tryride')->where(['applyuid'=>$value['id'],'status'=>['in','0,1']])
            // ->whereOr(function ($query) use ($whereOr) {
            //     $query->where($whereOr);
            // })->find();
            // if (!$tryride) {
            //     $list[$n]=$value;
            //     $n++;
            // }
        }
        unset($value);
        return array('list' => $list, 'tryrideinfo' => $tryrideinfo);
    }

    public function getuserinfo()
    {
        $params      = $this->request->post();
        $tryrideinfo = [];
        //查询历史试骑信息
        if ($params['sqr'] == 0) {
            $tryrideinfo = Db::name('tryride')
                ->where(['touid' => $params['uid']])
                ->field('tomobile as mobile,toaddress as address')
                ->order('id desc')
                ->find();
        } else {
            $tryrideinfo = Db::name('tryride')
                ->where(['applyuid' => $params['uid']])
                ->field('applymobile as mobile,applyaddress as address')
                ->order('id desc')
                ->find();
        }
        if (!$tryrideinfo) {
            $tryrideinfo = ['mobile' => '', 'address' => ''];
        }
        $this->success('', '', ['tryrideinfo' => $tryrideinfo]);
    }

    public function recyclebin()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->onlyTrashed()
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        foreach ($list as &$value) {
            $value['applyname'] = Db::name('user')->where('id', $value['applyuid'])->value('name');
            $value['toname']    = Db::name('user')->where('id', $value['touid'])->value('name');
        }
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    private function tryRideSend($uid, $txt): string
    {
        $service_account = ROOT_PATH . 'abandon/firebase/service_account.json';
        $user            = UserM::find($uid);
        $title           = "试骑通知";
        $title           = "Test Ride Notice";
        if($txt == '申请人'){
            $body = '系统客服给您（申请人）创建了试骑，请及时查看！';
            $body = 'The system customer service has created a test ride for you (applicant), please check it promptly!';
        }else{
            $body = '系统客服给您（被申请人）创建了试骑，请及时查看！';
            $body = 'The system customer service has created a test ride for you (the respondent), please check it promptly!';
        }
        $r1 = '';
        if ($user['android_token']) {
            try {
                (new Factory)
                    ->withServiceAccount($service_account)
                    ->createMessaging()
                    ->send(CloudMessage::withTarget('token', $user['android_token'])
                        ->withNotification(Notification::create($title, $body))
                        ->withData(['key' => 'value']));
                $r1 = '安卓:成功';
            } catch (Throwable $e) {
                $r1 = '安卓:' . $e->getMessage();
            }
        }
        $r2 = '';
        if ($user['apple_token']) {
            try {
                (new Factory)
                    ->withServiceAccount($service_account)
                    ->createMessaging()
                    ->send(CloudMessage::withTarget('token', $user['apple_token'])
                        ->withNotification(Notification::create($title, $body))
                        ->withData(['key' => 'value']));
                $r2 = '苹果:成功';
            } catch (Throwable $e) {
                $r2 = '苹果:' . $e->getMessage();
            }
        }
        return $r1 . ' ' . $r2;
    }
}
